<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <iframe src="./iframe1.html" id="ifr"></iframe>
    <iframe src="./iframe2.html" id="ifr2"></iframe>
    <script src="../../dist/asyncMessager.js"></script>
    <script>

        const iframe1 = document.getElementById("ifr");
        const iframe2 = document.getElementById("ifr2");

        function sendMessage(msg, iframe) {
            iframe.contentWindow.postMessage(msg)
        }

        const asyncMessager = new AsyncMessager.BaseAsyncMessager({
            subscribe(onMessage) {
                function onIframeMessage(msg) {
                    onMessage(msg.data);
                }
                window.addEventListener("message", onIframeMessage);
                return () => {
                    window.removeEventListener("message", onIframeMessage);
                }
            },
            request(data, key, iframe) {
                sendMessage(data, iframe);
            }
        });


        // scope: iframe1
        iframe1.contentWindow.onload = () => {
            asyncMessager.invoke({
                method: "init",
                // scope: "iframe1",
                _key_: "ifr1-1",
                data: {
                    user: 123456,
                    token: "blabla......",
                }
            }, {}, iframe1).then(res => console.log(`rq iframe1 , message from ${res.data.source}.html:`, res))
        }


        // scope: iframe2
        iframe2.contentWindow.onload = () => {
            asyncMessager.invoke({
                method: "init",
                // scope: "iframe2",
                _key_: "ifr2-1",
                data: {
                    user: 123456,
                    token: "blabla......"
                }
            }, {}, iframe2).then(res => console.log(`rq iframe2 ,message from ${res.data.source}.html:`, res))
        }

        // 没有scope
        // asyncMessager.addHandler("timeInfo", function (data) {
        //     console.log("index.html:timeInfo", data);
        // })


    </script>


</body>

</html>